package com.we823.cms.repository.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.we823.cms.common.web.pageable.PageRequest;
import com.we823.cms.common.web.pageable.Sort;
import com.we823.cms.model.BaseModel;
import tk.mybatis.mapper.common.Mapper;

import java.io.Serializable;
import java.util.List;

public abstract class AbstractBaseService<T extends BaseModel<ID>, ID extends Serializable> implements BaseService<T, ID> {

	private Mapper<T> mapper;
	
	public AbstractBaseService(Mapper<T> mapper) {
		this.mapper = mapper;
	}

	@Override
	public int add(T entity) {
		return mapper.insertSelective(entity);
	}

	@Override
	public int edit(T entity, ID id) {
		if (id==null){
			return mapper.insert(entity);
		}else{
			return mapper.updateByPrimaryKey(entity);
		}
	}

	@Override
	public void delete(ID key) {
		mapper.deleteByPrimaryKey(key);
	}

	@Override
	public T findOne(ID key) {
		return mapper.selectByPrimaryKey(key);
	}

	@Override
	public List<T> findAll() {
		return mapper.selectAll();
	}

	@Override
	public List<T> findAll(Sort sort) {
		setSortInfo(sort);
		return mapper.selectAll();
	}

	@Override
	public PageInfo<T> findAll(PageRequest pageRequest) {
		setPageInfo(pageRequest);
		return new PageInfo<>(mapper.selectAll());
	}

	/**
	 * 设置分页信息
	 * @param pageRequest 分页对象
	 */
	public void setPageInfo(PageRequest pageRequest) {
		if (pageRequest != null) {
			List<Sort> sorts = pageRequest.getSortList();
			if(sorts!=null && sorts.size()>0){
				List<String> orderByList = Lists.newArrayList();
				for (Sort sort : sorts) {
					orderByList.add(sort.getColumn() +" "+sort.getDirection().getName());
				}
				String result = String.join(",", orderByList);
				PageHelper.orderBy(result);

			}else{
				Sort sort = pageRequest.getSort();
				if (sort != null) {
					PageHelper.orderBy(sort.getColumn() + " " + sort.getDirection().getName());
				}
			}
			Integer pageSize = pageRequest.getPageSize();
			if(pageSize>0){
				PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize(), pageRequest.getCountable());
			}

		}
	}

	public void setSortInfo(Sort sort) {
		if (sort != null) {
			PageHelper.orderBy(sort.getColumn() + " " + sort.getDirection().getName());
		}
	}

}
